var _ = require('lodash')

export default {
  LOCALSTORAGE_KEY: 'drawTool',

  setLocalstorageItem(key, value) {
    let itemValue = localStorage.getItem(this.LOCALSTORAGE_KEY)
    let itemObject = {}
    if (itemValue !== null && itemValue !== '') {
      itemObject = JSON.parse(itemValue)
    }
    _.set(itemObject, key, value)
    itemValue = JSON.stringify(itemObject)
    localStorage.setItem(this.LOCALSTORAGE_KEY, itemValue)
  },

  removeLocalstorageItem(key) {
    let itemValue = localStorage.getItem(this.LOCALSTORAGE_KEY)
    let itemObject = {}
    if (itemValue !== null && itemValue !== '') {
      itemObject = JSON.parse(itemValue)
    }
    _.unset(itemObject, key)
    itemValue = JSON.stringify(itemObject)
    localStorage.setItem(this.LOCALSTORAGE_KEY, itemValue)
  },

  getLocalstorageItem(key) {
    const itemValue = localStorage.getItem(this.LOCALSTORAGE_KEY)
    let itemObject = {}
    if (itemValue !== null && itemValue !== '') {
      itemObject = JSON.parse(itemValue)
    }
    return _.get(itemObject, key)
  },

  clearLocalstorageItem() {
    localStorage.removeItem(this.LOCALSTORAGE_KEY)
  },

  // 将style属性值转换为对应的对象格式
  formatStrStyle2ObjStyle(strStyle) {
    const result = {}
    const styles = _.split(strStyle, ';')
    for (const style of styles) {
      const values = _.split(style, ':')
      if (values.length === 2) {
        _.set(result, values[0], values[1])
      }
    }
    return result
  },

  // 将对象格式的style转换为对应的字符串格式
  formatObjStyle2StrStyle(objStyle) {
    let result = ''
    _.forOwn(objStyle, function(value, key) {
      result += key + ':' + value + ';'
    })
    return result
  }
}
